import os

from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import QThread
from loguru import logger

from business.business import Business
from business.list_item import CustomQListWidgetItem
from business.role_name_ui import RoleName
from ui.main_ui import Ui_MainWindow
from business.work import VoiceWork, AllTextWork
from utils import model, utils

__dir__ = os.path.dirname(__file__)


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.business = Business()
        self.ui = Ui_MainWindow()
        self.setup_ui()
        self.role_widget = RoleName()
        self.role_widget.SignalRoleName.connect(self.add_new_role)
        self.one_thread = QThread()
        # 左边单独的合成线程
        self.voice_worker = VoiceWork()
        self.voice_worker.count_signal.connect(self.enable_he_cheng_button)
        # 整体合成单独的线程
        self.play_all_worker = AllTextWork(self.ui.listWidget)
        self.play_all_worker.count_signal.connect(self.enable_play_all_button)
        self.play_all_worker.slider.connect(self.change_slider)
        self.play_all_worker.play_all_failed.connect(self.play_all_thread_failed)

    def setup_ui(self):
        self.ui.setupUi(self)
        self.ui.tabWidget.setCurrentIndex(0)
        self.ui.textEdit.setText('这是实验文本。\n这是实验文本2')
        self.ui.tabWidget.currentChanged.connect(self.update_item)
        self.set_combo_box()
        self.ui.voice_comboBox.addItems(self.business.support_tts.keys())
        # connect
        self.ui.voice_comboBox.currentTextChanged.connect(self.set_combo_box)
        self.ui.role_comboBox.addItems(self.business.role_config_model.keys())
        self.set_role_combo_box()
        self.ui.role_comboBox.currentTextChanged.connect(self.set_role_combo_box)
        # 新建角色
        self.ui.new_role_Button.clicked.connect(self.get_now_role_name)
        # 更新角色
        self.ui.update_role_Button.clicked.connect(self.update_role_config)
        # 合成按钮
        self.ui.hecheng_pushButton.clicked.connect(self.he_cheng_tts)
        self.ui.hecheng_textEdit.setText('这是默认的文字')
        # 整体合成按钮
        self.ui.play_all_pushButton.clicked.connect(self.play_all_text)
        self.ui.play_horizontalSlider.setRange(0, 100)
        self.ui.play_all_widget.setStyleSheet('''QWidget{background-color:rgb(255, 255, 255);}''')

    def play_all_thread_failed(self):
        self.ui.play_all_widget.setStyleSheet('''QWidget{background-color:rgb(255, 0, 255);}''')

    def enable_he_cheng_button(self):
        self.ui.hecheng_pushButton.setEnabled(True)
        self.ui.complete_open_checkBox.setEnabled(True)
        self.ui.auto_play_checkBox.setEnabled(True)

    def enable_play_all_button(self):
        self.ui.play_all_pushButton.setEnabled(True)
        self.ui.complete_open_checkBox.setEnabled(True)
        self.ui.auto_play_checkBox.setEnabled(True)

    def change_slider(self, count: int):
        self.ui.play_horizontalSlider.setValue(count)

    def he_cheng_tts(self):
        self.ui.hecheng_pushButton.setEnabled(False)
        self.ui.complete_open_checkBox.setEnabled(False)
        self.ui.auto_play_checkBox.setEnabled(False)
        self.voice_worker.voice_model = model.VoiceModel(
            voice=self.ui.voice_comboBox.currentText(),
            style=self.ui.style_comboBox.currentText(),
            rate=self.ui.rate_spinBox.text(),
            pitch=self.ui.pitch_spinBox.text(),
            text=self.ui.hecheng_textEdit.toPlainText())
        self.voice_worker.auto_play_flag = self.ui.auto_play_checkBox.isChecked()
        self.voice_worker.complete_open_flag = self.ui.complete_open_checkBox.isChecked()
        self.voice_worker.start()

    def play_all_text(self):
        self.ui.play_all_pushButton.setEnabled(False)
        self.ui.complete_open_checkBox.setEnabled(False)
        self.ui.auto_play_checkBox.setEnabled(False)
        self.ui.play_horizontalSlider.setValue(0)
        self.ui.play_all_widget.setStyleSheet('''QWidget{background-color:rgb(255, 255, 255);}''')
        self.play_all_worker.auto_play_flag = self.ui.auto_play_checkBox.isChecked()
        self.play_all_worker.complete_open_flag = self.ui.complete_open_checkBox.isChecked()
        self.play_all_worker.start()

    def update_role_config(self):
        role_name = self.ui.role_comboBox.currentText()
        role_model = model.RoleConfig(
            voice=self.ui.voice_comboBox.currentText(),
            style=self.ui.style_comboBox.currentText(),
            rate=self.ui.rate_spinBox.text(),
            pitch=self.ui.pitch_spinBox.text()
        )
        self.business.role_config_model[role_name] = role_model
        self.set_role_combo_box(role_name)

    def add_new_role(self, role_name):
        role_model = model.RoleConfig(
            voice=self.ui.voice_comboBox.currentText(),
            style=self.ui.style_comboBox.currentText(),
            rate=self.ui.rate_spinBox.text(),
            pitch=self.ui.pitch_spinBox.text()
        )
        self.business.role_config_model[role_name] = role_model
        self.business.write_role_model()
        self.ui.role_comboBox.clear()
        self.ui.role_comboBox.addItems(self.business.role_config_model.keys())

    def get_now_role_name(self):
        self.role_widget.ui.lineEdit.clear()
        self.role_widget.show()

    def update_item(self):
        index = self.ui.tabWidget.currentIndex()
        logger.info('switch tab to {}'.format(index))
        if index == 0:
            content = ''
            for item in self.business.text_dict.values():
                content += "<{}>{}\n".format(item.role, item.text)
                self.ui.textEdit.setText(content)
        elif index == 1:
            self.ui.listWidget.destroy()
            self.ui.listWidget.clear()
            text_list = [i.strip() for i in self.ui.textEdit.toPlainText().split('\n') if i.strip()]
            self.business.item_list = []
            for i, value in enumerate(text_list):
                # 在listWidget中加入两个自定义的item
                role = utils.get_role_name(value)
                if role:
                    value = value[len(role) + 2:]
                else:
                    role = self.ui.role_comboBox.currentText()
                self.business.text_dict[i] = model.ListItem(role=role, text=value)
                item1 = CustomQListWidgetItem(i)
                self.business.item_list.append(item1)
                self.ui.listWidget.addItem(item1)
                self.ui.listWidget.setItemWidget(item1, item1.widget)

    def set_role_combo_box(self, role=None):
        origin = self.ui.role_comboBox.currentText()
        role_name = role or origin or list(self.business.role_config_model.keys())[0]
        role_model = self.business.role_config_model[role_name]
        self.ui.role_volice.setText(role_model.voice)
        self.ui.role_rate.setText(str(role_model.rate))
        self.ui.role_pitch.setText(str(role_model.pitch))
        self.ui.role_style.setText(role_model.style)

    def set_combo_box(self, name=None):
        self.ui.style_comboBox.clear()
        origin = self.ui.voice_comboBox.currentText()
        name = name or origin or list(self.business.support_tts.keys())[0]
        self.ui.style_comboBox.addItems(self.business.support_tts[name].style)
        self.set_role_combo_box()
